package com.yxy.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.yxy.base.BusinessException;
import com.yxy.dao.TenantExtendMapper;
import com.yxy.dto.system.TenantListDto2;
import com.yxy.feign.AuthService;
import com.yxy.feign.VO.AdminUserInToken;
import com.yxy.feign.authModel.Tenant;
import com.yxy.model.TenantExtend;
import com.yxy.utils.PageDataList;
import com.yxy.utils.TokenCheckUtil;
import com.yxy.vo.TenantVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 系统管理------- tenant管理
 * @author yuxiaoyang
 */
@Service
public class TenantService {

  @Autowired
  private TokenCheckUtil tokenCheckUtil;

  @Autowired
  private AuthService authService;

  @Resource
  private TenantExtendMapper tenantExtendMapper;

  public PageDataList<TenantVO> getList(TenantListDto2 query) throws BusinessException {
    AdminUserInToken adminUser = tokenCheckUtil.getUserInfoByToken();
    List<TenantVO> resultList = new ArrayList<>();
    Set<Long> tenantIdList = adminUser.getTenantIdList();

    query.setTenantIdList(tenantIdList);
    PageHelper.startPage(query.getPageNumber(), query.getPageSize());
    PageHelper.orderBy("t1.create_date desc");//排序
    List<TenantExtend> dbResult = tenantExtendMapper.selectList(query);
    Page<TenantExtend> dbResultPage = (Page<TenantExtend>) dbResult;

    for (TenantExtend dbItem : dbResultPage.getResult()) {
      TenantVO vo = new TenantVO();
      BeanUtils.copyProperties(dbItem, vo);
      Tenant authTenant = authService.getTenantById(vo.getId()).getContent();
      BeanUtils.copyProperties(authTenant, vo);
      resultList.add(vo);
    }

    PageDataList<TenantVO> pageDataList = new PageDataList<>(dbResultPage.getTotal(),
            dbResultPage.getPages(),
            dbResultPage.getPageNum(), dbResultPage.getPageSize());
    pageDataList.setList(resultList);
    return pageDataList;
  }

  public Object update(TenantExtend inputDto) {
    return tenantExtendMapper.updateByPrimaryKeySelective(inputDto);
  }
}
